package com.nervenets.web.controller.handler.user.user;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.controller.handler.user.UserModel;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;

public class UserInfoEditHandler extends Handler<UserInfoEditParams> {
    @Override
    public String handle(UserInfoEditParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getUserId(), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                User user = userDao.findById(params.getUserId(), User.class);
                if (null == user) return errorMessage(MessageCode.code_404);
                if (params.getAreaId() > 0) {
                    user.setAreaId(params.getAreaId());
                }
                if (!StringUtils.isEmpty(params.getAvatar())) {
                    user.setAvatar(params.getAvatar());
                }
                userDao.saveOrUpdate(user);
                globalService.clearRedisUserStored(params.getUserId());
                return successMessage(new UserModel(user, 1, globalVariablesService.getGlobalRule().getDefaultAvatar()));
            }
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
